package SBLib;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;



/**
 * Class only consists of static methods. 
 * 
 * - Used as a library to encode and decode JSON strings. 
 * - Server will encode all Files filenames and filecontents into JSON string
 * - Client will decode the JSON string into an ArrayList of Files
 * @author BrandonNeal
 */
public class JsonFile {

    /**
     * Server calls this to encode list of Files into JSON String
     * @param files Files to encode
     * @return JSON string of {filename:filecontent}
     */
    public static JSONObject FileListToJson(ArrayList<File> files)
    {
        JSONObject json = new JSONObject();
        for(File f:files)
        {
            json.put(f.getFileName(), f.getFileContent());
        }
        return json;
    }
    /**
     * 
     * @param jsonText Encoded files
     * @return ArrayList<File>
     */
    public static ArrayList<File> JsonTextToFileList(String jsonText)
    {
        ArrayList<File> files = new ArrayList<File>();
        try 
        {
            JSONParser parser=new JSONParser();
            Map map = (Map)parser.parse(jsonText);
            Iterator iter = map.entrySet().iterator();
            while(iter.hasNext())
            {
                Map.Entry entry = (Map.Entry)iter.next();
                //System.out.println(entry.getKey() + "=>" + entry.getValue());
                File f = new File();
                f.setFileName((String)entry.getKey());
                f.setFileContent((String)entry.getValue());
                files.add(f);
            }
        } 
        catch (ParseException ex)
        {
            Logger.getLogger(JsonFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        return files;
    }
    
}
